<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Mprogram extends MY_Model
{
    public function __construct()
    {
        parent::__construct();
    }
    
    
    public function getCampaign()
    {
        $sql = "SELECT id,campaign FROM campaigns";
        $query = $this->db->query($sql);
        $data = $query->result_array();
        
        $arr = array();
        foreach($data AS $key => $value)
        {
            $arr[$value['id']] = $value['campaign'];
        }
        return $arr; 
    }
    
    public function getQuestion($campaign_id)
    {
        $sql = "SELECT id,stt,content FROM questions WHERE id_campaign = '".$campaign_id."' ORDER BY stt ASC";
        $query = $this->db->query($sql);
        $data = $query->result_array();
        //echo '<pre>'; 
        //die(print_r($data));
        
        $count = sizeof($data);
        $arr = array();
        $i = 0;
        foreach($data AS $key=>$value)
        {
            $arr[$i] = json_decode($value['content']);
            $arr[$i]->id = $value['id'];
            $arr[$i]->stt = $value['stt'];
            $i = $i + 1;
        }
        
        /*
        $_db = $this->db->query('SELECT content FROM setting WHERE type = "monthPlay"')->row_object()->content;
        $exp = explode('|', $_db);
        $month_db = intval($exp[0]);
        //$data = $this->db->query('SELECT u.username, sl.scores, sl.time, u.fullname FROM `user` AS u INNER JOIN score_logs AS sl ON sl.user_id = u.id WHERE sl.`campaign_id` = '.$campaign_id.' sl.scores DESC, sl.time ASC LIMIT 10')->result_object();
        $data_ = $this->db->query('SELECT u.username, sl.scores, sl.time, u.fullname FROM `user` AS u INNER JOIN score AS sl ON sl.user_id = u.id ORDER BY sl.scores DESC, sl.time ASC LIMIT 10')->result_object();
        
        foreach($data_ AS $el=>$le)
        {
            $data_[$el]->name   = $le->fullname ? $le->fullname : $le->username;
            $data_[$el]->times  = $this->convertSecond($le->time);
        }
        return array('arr' =>json_encode($arr), 'count' =>$count, 'bxh' => json_encode($data_));
        */ //Nhatnv commnet vi da tra ra bxh sau click update
        
        return array('arr' =>json_encode($arr), 'count' =>$count);
    }
    
    public function getBxh()
    {
        $_db = $this->db->query('SELECT content FROM setting WHERE type = "monthPlay"')->row_object()->content;
        $exp = explode('|', $_db);
        $month_db = intval($exp[0]);
        $data_ = $this->db->query('SELECT u.username, sl.scores, sl.time, u.fullname FROM `user` AS u INNER JOIN score AS sl ON sl.user_id = u.id ORDER BY sl.scores DESC, sl.time ASC LIMIT 10')->result_object();
        $html = '';
        foreach($data_ AS $el=>$le)
        {
            $name = '';
            $name = $le->fullname ? $le->fullname : $le->username;
            $html .= '<tr><td>'.($el+1).'.<a title="'.$name.'">'.$name.'</a></td>';
            $html .= '<td>'.$le->scores.'</td>';
            $html .= '<td>'.$this->convertSecond($le->time).'</td></tr>';
        }
        
        return (object)array('bxh' => $html);
    }
    
    public function newSession()
    {
        $this->db->query("TRUNCATE score");
        $this->db->query("TRUNCATE logs");
        $this->db->update('number_play_current', array('numberQuestion' => null, 'numberGameshow' => 0));
        return 200;   
    }
    
    public function updateCampQuest($campaign, $question)
    {
         $data = array(
            'numberQuestion' => $question,
            'numberGameshow' => $campaign
        );
        $this->db->update('number_play_current', $data);   
        
        /**
         * @void Cập nhật lại thời gian tháng chơi hiện tại
         */                                  
        $month_current = $this->db->query('SELECT content FROM setting WHERE type = "monthPlay"')->row_object()->content;
        
        $month_date = intval(date('m'));
        $year_date  = intval(date('Y'));
        
        $exp = explode('|', $month_current);
        
        $month_db   = intval($exp[0]);
        $month_db_  = intval($exp[1]);
        $year_db    = intval($exp[2]);
        
        if($year_date > $year_db)
        {
            $date_it = array('content' => ($month_db + 1).'|'.$month_date.'|'.$year_date);
            $this->db->update('setting', $date_it, "type = 'monthPlay'");
            
            $ids_ = $this->deleteScoreLogs($month_db);
            $this->db->query('DELETE FROM score_logs WHERE id NOT IN ('.$ids_.') AND month = '.$month_db);
            
        }else if($month_date > $month_db_)
        {
            $date_it = array('content' => ($month_db + 1).'|'.$month_date.'|'.$year_db);
            $this->db->update('setting', $date_it, "type = 'monthPlay'");
            
            $ids_ = $this->deleteScoreLogs($month_db);
            $this->db->query('DELETE FROM score_logs WHERE id NOT IN ('.$ids_.') AND month = '.$month_db);
            
        }      
        //$this->db->update('score_logs', array('month' => $month_db), "campaign_id = ".$campaign);
      //  die($campaign.'--'.$month_db); 
        
    }
    
    private function deleteScoreLogs($month_db)
    {
        $data = $this->db->query('SELECT id, `month` FROM score_logs WHERE `month` = '.$month_db.' GROUP BY user_id ORDER BY scores DESC, time ASC LIMIT 10')->result_object();
        $id_ = '';
        foreach($data AS $el=>$le)
        {
            $id_ .= ',"'.$le->id.'"';
        }
        
        return substr($id_, 1);   
    }
    
    public function updateTimeSend($delay)
    {
        //sleep($delay); Nhatnv comment vì đã trừ 3 giây khi click trả lời
        $time_send = $this->microtime_float();
        $this->db->update('time_send', array('time_send' => $time_send));
    }
    
    
    public function getIndex($number = 0,$offset = 0)
    {
        $limit = $offset ? intval($offset) : '0';
        
        $sql = "SELECT * FROM campaigns ORDER BY id DESC";
        
        $count = $this->db->query($sql)->num_rows();
        if($offset >= $count && $count != 0){
            $this->load->view('template/404',$this->data);
            return false;
        }
        
        $xdata = " LIMIT ".$limit.",".$number." ";
        $xs = $this->db->query($sql.$xdata)->result_object();
        return array('data' => $xs, 'count' => $count);
    }
    
    public function addThisProgram($title)
    {
        $title_ascii = $this->get_ascii($title);
        $data = array(
            'campaign' => $title,
            'campaign_ascii' => $title_ascii,
            'created' => date('Y-m-d H:i:s')
        );
        $count = $this->db->query("SELECT id FROM campaigns WHERE campaign_ascii = '".$title_ascii."'")->num_rows();
        if($count == 0)
        {
            $this->db->insert('campaigns', $data);
            return 200;   
        }
        return 100;
    }
    
    public function getThisProgram($id)
    {
        $data = $this->db->query("SELECT campaign FROM campaigns WHERE id = '".$id."'")->row_array();
        return $data;
    }
    public function editThisProgram($title, $id)
    {
        $title_ascii = $this->get_ascii($title);
        $data = array(
            'campaign' => $title,
            'campaign_ascii' => $title_ascii,
            'created' => date('Y-m-d H:i:s')
        );
        $count = $this->db->query("SELECT id FROM campaigns WHERE campaign_ascii = '".$title_ascii."'")->num_rows();
        if($count == 0)
        {
            $this->db->update('campaigns', $data, "id = '".$id."'");
            return 200;   
        }
        return 100;
    }
    
    public function deleteThisProgram($id)
    {
        $this->db->delete('campaigns', "id = '".$id."'");
        $this->db->delete('questions', "id_campaign = '".$id."'");
    }
    
    public function getDetailProgram($id)
    {
        $sql = "SELECT q.id,q.stt,q.content,c.campaign  FROM questions AS q LEFT JOIN campaigns AS c ON c.id = q.id_campaign WHERE q.id_campaign = '".$id."' ORDER BY q.stt ASC";
        $data = $this->db->query($sql)->result_array();
        //echo '<pre>';
        //die(print_r($data));
        return $data;
    }
    
    public function addThisQuestion($id_campaign,$stt,$question,$choice1,$choice2,$choice3,$choice4,$answer)
    {
        $q = array('question' => $question);
        $x = array('choice' => $as = array(
            '1' => $choice1,
            '2' => $choice2,
            '3' => $choice3,
            '4' => $choice4
        ));
        $arr = json_encode(array_merge($q, $x));
        
        $data = array(
            'stt' => $stt,
            'content' => $arr,
            'answer' => $answer,
            'id_campaign' => $id_campaign,
            'created' => date('Y-m-d H:i:s')
        );
        //echo '<pre>';
        //die(print_r($arr));
        $count = $this->db->query("SELECT id FROM questions WHERE id_campaign = '".$id_campaign."' AND stt = '".$stt."'")->num_rows();
        if($count == 0)
        {
            $this->db->insert('questions', $data);
            return 200;   
        }
        return 100;
    }
    
    public function getThisQuestion($id)
    {
        $data = $this->db->query("SELECT q.*,c.campaign,c.id AS idc FROM questions AS q LEFT JOIN campaigns AS c ON c.id = q.id_campaign WHERE q.id = '".$id."'")->row_array();
        return $data;
    }
    public function editThisQuestion($id,$id_campaign,$question,$choice1,$choice2,$choice3,$choice4,$answer)
    {
        $q = array('question' => $question);
        $x = array('choice' => $as = array(
            '1' => $choice1,
            '2' => $choice2,
            '3' => $choice3,
            '4' => $choice4
        ));
        $arr = json_encode(array_merge($q, $x));
        
        $data = array(
            'content' => $arr,
            'answer' => $answer,
            'created' => date('Y-m-d H:i:s')
        );
        $this->db->update('questions', $data, "id = '".$id."'");
        return 200;
    }
    
    public function deleteThisQuestion($id)
    {
        $this->db->delete('questions', "id = '".$id."'");
    }
    
    public function fillterPlayer()
    {
        $question = intval($this->getParamInt('question'));
        if($question == 1)
        {
            $where = 'AND answer < '.intval($question - 1).' OR answer IS NULL';
        }else{
            $where = 'AND answer < '.$question;
        }
        echo "UPDATE score SET stop = 1 WHERE 1=1 ".$where;
        $this->db->query("UPDATE score SET stop = 1 WHERE 1=1 ".$where);
    }
    
    public function copyScore($id)
    {
        $_db = $this->db->query('SELECT content FROM setting WHERE type = "monthPlay"')->row_object()->content;
        $exp = explode('|', $_db);
        $month_db = intval($exp[0]);
        
        $data = $this->db->query('SELECT * FROM score ORDER BY id ASC')->result_object();
        foreach($data AS $el=>$le)
        {
            $data = array(
                    'user_id' => $le->user_id,
                    'scores' => $le->scores,
                    'time' => $le->time,
                    'stop' => $le->stop,
                    'campaign_id' => $id,
                    'month' => $month_db,
                    'answer' => $le->answer
            );
            $this->db->insert('score_logs', $data);
        }
        
        
        $_db = $this->db->query('SELECT content FROM setting WHERE type = "monthPlay"')->row_object()->content;
        $exp = explode('|', $_db);
        $month_db = intval($exp[0]);
        $data_ = $this->db->query('SELECT u.username, sl.scores, sl.time, u.fullname FROM `user` AS u INNER JOIN score AS sl ON sl.user_id = u.id ORDER BY sl.scores DESC, sl.time ASC LIMIT 1')->result_object();
        $html = '<table style="width: 100%;"><thead><tr><th>Người chơi</th><th>Điểm</th><th>Thời gian</th></tr></thead><tbody id="list-bxh">';
        foreach($data_ AS $el=>$le)
        {
            $name = '';
            $name = $le->fullname ? $le->fullname : $le->username;
            $html .= '<tr><td>'.($el+1).'.<a title="'.$name.'" href="#">'.$name.'</a></td>';
            $html .= '<td>'.$le->scores.'</td>';
            $html .= '<td>'.$this->convertSecond($le->time).'</td></tr>';
        }
        $html .= '</tbody></table><style>table{margin-top:20px}th{text-align: left;padding: 5px;border-bottom: 1px #ccc solid;}td{text-align: left;padding: 5px;}</style>';
        return (object)array('stt' => '200', 'data' => $html);
    }

}
